<?php

if( !isset( $_GET['scriptid'] ) )
	exit;
else
	$script_id = (int)stripslashes( $_GET['scriptid'] );

if ( !$script_id > 0 )
	exit;

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'http://userscripts.org/scripts/source/' . $script_id . '.meta.js' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$output = curl_exec( $ch );
curl_close( $ch );

preg_match_all( '/@(\S+?)(?::(\S+))?(?:[ \t]+([^\r\n]+)|\s+)/', $output, $meta );

foreach ( $meta[1] as $key => $value ) {
	if ( $meta[2][ $key ] && strlen( $meta[2][ $key ] ) > 0 ) {
		$meta_array[ $value ][ $meta[2][ $key ] ] = $meta[3][ $key ];
		$meta_safe[ $value ][ $meta[2][ $key ] ] = addslashes ( $meta[3][ $key ] );
	}
	else if ( is_string( $meta_array[ $value ] ) ) {
		$meta_array[ $value ] = array(
			$meta_array[ $value ],
			$meta[3][ $key ]
		);
		$meta_safe[ $value ] = array(
			$meta_array[ $value ],
			addslashes( $meta[3][ $key ] )
		);
	}
	else if ( is_array( $meta_array[ $value ] ) ) {
		$meta_array[ $value ][] = $meta[3][ $key ];
		$meta_safe[ $value ][] = addslashes( $meta[3][ $key ] );
	}
	else {
		$meta_array[ $value ] = $meta[3][ $key ];
		$meta_safe[ $value ] = addslashes( $meta[3][ $key ] );
	}
}

$meta = $meta_safe;
$meta_string = json_encode( $meta_array );
unset( $meta_array );

if( isset( $_GET['interval'] ) )
	$days = (int)( stripslashes( $_GET['interval'] ) );
else
	$days = 7;

if ( $days < 1 )
  $days = 7;

if ( isset( $meta["unlisted"] ) )
  $_GET["update"] = "show";

switch ( isset( $_GET["update"] ) ? strtolower( $_GET["update"] ) : "show" ) {
	case 'update':
		$update_url = "https://userscripts.org/scripts/source/" . $script_id . ".user.js?update.user.js";
		break;
	case 'install':
		$update_url = "https://userscripts.org/scripts/source/" . $script_id . ".user.js";
		break;
	case 'show':
	default:
		$update_url = "http://userscripts.org/scripts/show/" . $script_id . "/";
		break;
}

require_once 'lib/classes/language.php';

if( isset( $_GET['lang'] ) )
	$uso_language = new USO_language( stripslashes( $_GET['lang'] ) );
else
	$uso_language = new USO_language();

$uso_language->strings = array(
	// English
	"en"	=>	array(
		"update_available"		=>	"An update is available for this script. Do you want to update now?",
		"update_unavailable"	=>	"Has no updates available at this current time.",
		"menu_update_check"		=>	"Check for updates.",
		"menu_updater_toggle"	=>	"Toggle auto updates.",
		"updater_off"			=>	"Automatic Updates are now off.",
		"updater_on"			=>	"Automatic Updates are now on."
	)
);
$uso_language->default = "en";

$locale = $uso_language->translate();

header( 'Content-Type: application/x-javascript; charset=utf-8' );

?>// @name        USO @require Updater
// @copyright   Copyright (c) 2009, Tim Smart, All Rights Reserved
// @license     http://usoupdater.googlecode.com/svn/trunk/license.txt
// @revision    50
// @changelog   http://code.google.com/p/usoupdater/source/list

if ( typeof USO !== "object" )
  USO = {};
USO.updater = (function() {
  var uso_updater = {
    increment: parseInt(GM_getValue("uso_updater/last_increment", 0)),
    interval: 7 * 60 * 60,
    details: {
      scriptID: "<?=$script_id?>",
      updateURI: "<?=$update_url?>",
      scriptName: "<?=$meta["name"]?>",
      remoteMeta: <?=$meta_string?>,
      currentVersion: parseInt("<?=$meta["uso"]["version"]?>"),
      locale: {
        updateAvailable: "<?=$locale['update_available']?>",
        updateUnavailable: "<?=$locale['update_unavailable']?>"
      }
    },
    calculate_interval: function(max) {
      var hours = Math.round(Math.exp(this.increment) * (1 / (Math.exp(4) / 24)));
      max *= 24;
      if (150 < hours)
        hours = Math.round(hours / 168) * 168;
      else if (20 < hours)
        hours = Math.round(hours / 24) * 24;
      if (hours >= max)
        return max;
      return hours;
    },
    interval_check: function() {
      this.interval = this.calculate_interval(parseInt('<?=$days?>')) * 60 * 60;
      if (GM_getValue("uso_updater/enabled", true) &&
          ((new Date().getTime())/1000 - parseInt(GM_getValue("uso_updater/last_update", 1)) >= this.interval))
        this.version_check();
    },
    version_check: function(force) {
      GM_xmlhttpRequest({
        method: "GET",
        url: "https://userscripts.org/scripts/source/<?=$script_id?>.meta.js",
        onload: function(xhr) {
          uso_updater.version_compare(xhr.responseText, force);
        }
      });
    },
    version_compare: function(text, force) {
      var match = text.match(/@uso:version\s+(\d+)/),
        name = text.match(/@name\s+([^\r\n]+)/),
        namespace = text.match(/@namespace\s+([^\r\n]+)/);
      if (match && name) {
        this.details.newVersion = parseInt(match[1]);
        if (this.details.newVersion > this.details.currentVersion &&
            this.details.currentVersion >= parseInt(GM_getValue("uso_updater/new_version", 0))) {
          GM_setValue("uso_updater/last_increment", 1);
          GM_setValue("uso_updater/new_version", this.details.newVersion);
        }
        else if (!force)
          GM_setValue("uso_updater/last_increment", 1 + this.increment);
        if (name[1] !== this.details.scriptName || namespace[1] !== this.details.remoteMeta.namespace)
          GM_setValue("uso_updater/enabled", false);
        this.update(this.details, force?true:false);
      }
      else
        GM_setValue("uso_updater/enabled", false);
      GM_setValue("uso_updater/last_update", Math.floor((new Date().getTime())/1000));
    },
    update: function(details, forced) {
      if (details.newVersion > details.currentVersion) {
        if (confirm(details.scriptName + ": " + details.locale.updateAvailable))
          GM_openInTab(details.updateURI);
      }
      else if (forced)
        alert(details.scriptName + ": " + details.locale.updateUnavailable);
    }
  };
  try {
    if (typeof GM_xmlhttpRequest === "function" && top.location.href === location.href)
      uso_updater.interval_check();
  }
  catch (e) {
    if (typeof GM_xmlhttpRequest === "function")
      uso_updater.interval_check();
  }
  return {
    get registerMenuUpdate() { return function() {
      GM_registerMenuCommand(uso_updater.details.scriptName + ": <?=$locale['menu_update_check']?>",
                             function() { uso_updater.version_check(true); });
    };},
    get registerMenuToggle() { return function() {
        GM_registerMenuCommand(uso_updater.details.scriptName + ": <?=$locale['menu_updater_toggle']?>", function() {
          if (GM_getValue('uso_updater/enabled', true) === true) {
            alert(uso_updater.details.scriptName + ": <?=$locale['updater_off']?>");
            GM_setValue("uso_updater/enabled", false);
          }
          else {
            alert(uso_updater.details.scriptName + ": <?=$locale['updater_on']?>");
            GM_setValue("uso_updater/enabled", true);
          }
        });
    };},
    get registerCallback() { return function(callback) { uso_updater.update = callback; }; }
  };
})();